<?php
class Posts_Model_DbTable_Posts extends Zend_Db_Table_Abstract
{
    protected $_name = 'posts';
	
	/* lay danh sach posts */
	public function getPosts(){
    	$row = $this->fetchAll();
    	if (!$row) {
    		throw new Exception("Could not find row");
    	}
    	return $row->toArray();
    }
	
	/* 
	- Lay posts theo id
	- Chuyen id vao
	*/
	public function getByPostView($id){	
    	$id = (int)$id;
    	$row = $this->fetchRow('id = ' . $id);
    	if (!$row) {
    		throw new Exception("Could not find row $id");
    	}
    	return $row->toArray();
    }
	
	/*TODO: cap nhat so lan xem bai viet*/
	public function updateByPostView($id){	
    	$id = (int)$id;    	
    }
	

	/*
	Them cau hoi
	*/
	 public function addPost($post_author, $post_datetime, $post_content, $post_title,
							$post_status, $post_parent, $post_type, $post_view, $post_category,
							$meta_tile, $meta_image, $meta_link, $meta_content, $post_image
							)
    {

	    	$data = array(
    			'post_author' => $post_author,
    			'post_datetime' => $post_datetime,
    			'post_content' => $post_content,
    			'post_title' => $post_title,
    			'post_status' => $post_status,
    			// 'post_parent' => $post_parent,
    			'post_type' => $post_type,
    			'post_view' => $post_view,	
				'post_category' => $post_category,
				'meta_title' => $meta_tile,
				'meta_description' => $meta_content,
				'meta_images' => $meta_image,
				'post_image' => $post_image,
				'meta_link' => $meta_link				
				
				
    	);
		/*
		echo "<pre>";
		print_r($data);
		echo "</pre>";	
		exit;
		*/
    	return $this->insert($data);
		
    }
	
	public function updatePost($id, $post_author, $post_datetime, $post_content, $post_title,
					$post_status, $post_parent, $post_type, $post_view, $post_category)
    {
    	$data = array(
    			'post_author' => $post_author,
    			'post_datetime' => $post_datetime,
    			'post_content' => $post_content,
    			'post_title' => $post_title,
    			'post_status' => $post_status,
    			'post_parent' => $post_parent,
    			'post_type' => $post_type,
    			'post_view' => $post_view,	
				'post_category' => $post_category				
    	);

		echo "<pre>";
    	print_r ( $data);
    	echo "</pre>";
		
		$this->update($data, 'ID = '. (int)$id);
    }
	 public function deletePost($id)
    {
    	$this->delete('id =' . (int)$id);
		return 1;
    }
	
	 public function getListPosts($postuserid)
    {			
    	$row = $this->fetchall("post_author = $postuserid AND post_parent = 0 AND post_status=1");
    	if (!$row) {
    		throw new Exception("Could not find row ");
    	}
		
		$rowvalue = $row->toArray();
		
		/*
		echo "<pre>";
		print_r($rowvalue);
		echo "</pre>";
		exit;
		
			*/
	

	
		/* dag lam */
/*
				$db = Zend_Db_Table::getDefaultAdapter(); 
				$select = $db->select()
				 ->from(array('p' => 'posts'),
						array('post_datetime', 'post_title'))
				 ->join(array('u' => 'users'),
						'u.ID = p.post_author');
					*/
	$db = Zend_Db_Table::getDefaultAdapter(); 
			
											
		

		
//		exit;
				
							 
			/* end dang lam */
	
	
	
	
	
		$value=array();
		$value['row']= $rowvalue;
		foreach ($rowvalue AS $k => $row)
		{
			//$rowparent = $this->fetchall('post_status=1 AND post_parent ='.$row['ID']);			
		//	$value['rowparent'][$k] = $rowparent->toArray();
			
				$select = $db->select()
				 ->from(array('p' => 'posts'),
						array('ID','post_author AS user_id','post_datetime','post_content',
						'post_title'
						)
						)
						
				 ->join(array('u' => 'users'),
						'u.ID = p.post_author',
						array('user_name')
						)
						
				/*Hoan commend ngay 20120811*/
				 ->where('p.post_parent=?',$row['ID'])
				  ->where('p.post_status=?',1);
						
				$value['rowparent'][$k]  = $db->fetchAll($select);
				/*
								
						echo "<pre>";
						print_r($rows);
						echo "</pre>";
					*/
		
		}
    	return $value;
		
    }
	
	public function getListPostsByUser($postuserid, $like_user)
    {		

		$db = Zend_Db_Table::getDefaultAdapter(); 
    	$row = $this->fetchall("post_author = $postuserid AND post_status=1","ID desc");
    	if (!$row)
		{
    		throw new Exception("Could not find row ");
    	}
		$rowvalue = $row->toArray();
		
		$value=array();
		$value['row']= $rowvalue;
				
		foreach ($rowvalue AS $k => $row)
		{

				$str = "select ID from likes WHERE like_tables=1 AND like_tables_id=$row[ID] AND like_user=$like_user";
				$stmt = $db->query($str);
				$result = $stmt->fetch();	
			
				$value['row'][$k]['p_datetime'] = $this->convertdate($row['post_datetime']);
				$value['row'][$k]['like_status'] = $result['ID'];
				$value['row'][$k]['like'] = "Like";
				$value['row'][$k]['meta_base_url'] = $this->getbasedomain($row['meta_link']);
				
				if($result['ID'] != NULL)
				{
					$value['row'][$k]['like'] = "UnLike";
				}
				
				
			
			
				$str = "SELECT u.`user_name` FROM likes AS l, users AS u WHERE l.`like_user` = u.`ID`
						AND	like_tables=1 AND like_tables_id=$row[ID] AND l.`like_user` != $like_user";
				$stmt = $db->query($str);
				$result = $stmt->fetchAll();
				$value['userlike'][$k] = $result;
				
				$select = $db->select()
				 ->from(array('c' => 'comments'),
						array('ID','comment_author AS user_id','comment_postdate','comment_content')
						
						)
				
				 ->join(array('u' => 'users'),
						'u.ID = c.comment_author',
						array('user_name')
						)
					
				/*Hoan commend ngay 20120811*/
				 ->where('c.post_parent=?',$row['ID'])
				  ->where('c.comment_status=?',1);
					
				$value['rowparent'][$k]  = $db->fetchAll($select);
				
				foreach ($value['rowparent'][$k] AS $i=> $pr )
				{			
					$str = "select ID from likes WHERE like_tables=2 AND like_tables_id=$pr[ID] AND like_user=$like_user";
					$stmt = $db->query($str);
					$result = $stmt->fetch();										
					$value['rowparent'][$k][$i]['c_datetime'] = $this->convertdate($pr['comment_postdate']);
					$value['rowparent'][$k][$i]['like_status'] = $result['ID'];
					$value['rowparent'][$k][$i]['like'] = "Like";
					
					if($result['ID'] != NULL)
					{
						$value['rowparent'][$k][$i]['like'] = "UnLike";
					}
					
					$str = "SELECT u.`user_name` FROM likes AS l, users AS u WHERE l.`like_user` = u.`ID`
					AND	like_tables=2 AND like_tables_id=$pr[ID] AND l.`like_user` != $like_user";
					$stmt = $db->query($str);
					$result = $stmt->fetchAll();
					// $value['rowparent'][$k][$i]['userlike'] = $result;
					$value['rowparent'][$k][$i]['userlike'] = $result;
				}
				
		
			
		}
				
		/*
		echo "<pre>";
		print_r($value);
		echo "</pre>";
		exit;
		*/
    	return $value;
	}
	
	
	/*
	==> lay thoi gian hien thi cho cau hoi hoac binh luan
	@ngaythang: format:Y-m-d H:i:s
	return: values thoi gian
	$s = microtime(true);
	$e = microtime(true);
	echo $e - $s;
	*/
	public function convertdate($date)
    {

	// $date = '2012-08-01 09:31:40';
	$arrngaythang = array();
	$arrngaythang['nam'] = substr($date,0,4);
	$arrngaythang['thang'] = substr($date,5,2);
	$arrngaythang['ngay'] = substr($date,8,2);
	$arrngaythang['gio'] = substr($date,11,2);
	$arrngaythang['phut'] = substr($date,14,2);
	$arrngaythang['giay'] = substr($date,17,2);
	
	$timestamp=mktime($arrngaythang['gio'], $arrngaythang['phut'], $arrngaythang['giay'],
					$arrngaythang['thang'],$arrngaythang['ngay'], $arrngaythang['nam']);	
	// date('Y-m-d H:i:s',$timestamp); 
	
	
		$time = time();
					//(gi?, ph򴬠gi㹬 th⯧, ngṬ nam)
		// $timestamp=mktime(7,34,46,7,14,2012);	
		$seconds =  $time - $timestamp;
		
	//	return $seconds;
		switch ($seconds)
		{		
			case 0 :
			$showdate ="1 giây trước";
			break;
		
		//giay
			case $seconds < 60 :
			$showdate =$seconds." giây trước";
			break;
			
		//phut		
			case $seconds < 3600 :
			$showdate =round($seconds/60)." phút trước";
			break;
			
		//gio					
			case $seconds < 86400 :
			$showdate =round($seconds/3600)." giờ trước";
			break;
			
		//ngay
			case $seconds < 604800 :
			$showdate =round($seconds/86400)." ngày trước";;
			break;

		//tuan
			case $seconds < 2419200 :
			$showdate =round($seconds/604800)." tuần trước";
			break;
			
			default:
			$showdate =date('d/m/Y',$timestamp);  
			break;			
		}

		return $showdate;
	}
	
	/*
	==> Lay url goc cua link
	EX: $address='http://www.subdomain.example.com/blog/index.php?id=1';
	echo getbasedomain($address); // xuat ra example.com	
	*/
	public function getbasedomain($domainb)
	{
		$bits = explode('/', $domainb);
		if ($bits[0]=='http:' || $bits[0]=='https:')
		{
		$domainb= $bits[2];
		} else {
		$domainb= $bits[0];
		}
		unset($bits);
		$bits = explode('.', $domainb);
		$idz=count($bits);
		$idz-=3;
		if (strlen($bits[($idz+2)])==2) {
		$url=$bits[$idz].'.'.$bits[($idz+1)].'.'.$bits[($idz+2)];
		} else if (strlen($bits[($idz+2)])==0) {
		$url=$bits[($idz)].'.'.$bits[($idz+1)];
		} else {
		$url=$bits[($idz+1)].'.'.$bits[($idz+2)];
		}
		return $url;
	}
	
}

